Component({
  properties: {
    src: String
  },
  lifetimes: {
    attached() {
      this.HAVE_NOTHING = 0
      this.HAVE_METADATA = 1
      this.HAVE_CURRENT_DATA = 2
      this.HAVE_FUTURE_DATA = 3
      this.HAVE_ENOUGH_DATA = 4
      this.decoder = wx.createVideoDecoder()
      const animate = () => {
        const frameData = this.decoder.getFrameData()
        if (frameData == null) {
          return
        }
        const {
          data,
          width,
          height
        } = frameData
        const typedArray = new Uint8Array(data)
        this.frameData = {
          width,
          height,
          data: typedArray
        };
        if(this._requestVideoFrameCallback){
          this._requestVideoFrameCallback()
        }
      }
      var timer
      this.decoder.on("start", async () => {
        console.error("on.start")
        this._readyState = this.HAVE_CURRENT_DATA
        animate()
        timer = setInterval(() => {
          animate()
        }, 20)
      })
      this.decoder.on("stop", async () => {
        console.error("on.stop")
        clearInterval(timer)
      })
      this.decoder.on("seek", async () => {
       // console.error("on.seek")
      })
      this.decoder.on("ended", async () => {
        console.error("on.ended")
      })
      this.decoder.on("bufferchange", async () => {
        //console.error("on.bufferchange")
        this.decoder.seek(0)
      })
    },
    detached() {
      console.error("detached")
      this.decoder.stop()
      this.decoder.remove()
    }
  },
  methods: {
    get readyState() {
      return this._readyState
    },
    get isHTMLVideoElement() {
      return true
    },
    play() {
      this._readyState = this.HAVE_NOTHING
      // console.error("play",this.data.src)
      this.decoder.start({
        mode: 1,
        abortAudio: true,
        source: this.data.src
      })
    },
    stop() {
      this.decoder.stop()
      this.decoder.remove()
    },
    requestVideoFrameCallback(requestVideoFrameCallback) {
      this._requestVideoFrameCallback = requestVideoFrameCallback
    }
  }
})